package com.competition.web.admin.interceptor;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Signature;

import com.competition.web.admin.log.IOperatorLog;
import com.competition.web.admin.log.impl.DeleteLog;
import com.competition.web.admin.log.impl.InsertLog;
import com.competition.web.admin.log.impl.UpdateLog;

import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;

@Intercepts({
    @Signature(method = "update", type = Executor.class, args = {MappedStatement.class, Object.class}),
//    @Signature(method = "delete", type = Executor.class, args = {MappedStatement.class, Object.class}),
//    @Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class, Integer.class})
})
public class UserOperatorLog implements Interceptor {


	private static Map<Integer, IOperatorLog> map = new HashMap<>();
	
	static {
		map.put(SqlCommandType.UPDATE.ordinal(), new UpdateLog());
		map.put(SqlCommandType.DELETE.ordinal(), new DeleteLog());
		map.put(SqlCommandType.INSERT.ordinal(), new InsertLog());
	}
	
	@Override
	public Object intercept(Invocation invocation) throws Throwable {

		Object[] object = invocation.getArgs();
		
		MappedStatement mappedStatement =  (MappedStatement)(object[0]);
		
		BoundSql boundSql =  mappedStatement.getBoundSql(object[1]);
		
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        
        IOperatorLog operatorLog = map.get(sqlCommandType.ordinal());
        
        if (null == operatorLog) {
        	return 1;
        }
        
        int status = operatorLog.callBack(object[1],  boundSql, mappedStatement, invocation);
        if (0 == status) {
        	return  1;
        }
        // 执行原计划
        return invocation.getMethod().invoke(invocation.getTarget(), object);   
	}

}
